package com.local.admin.controller;

import com.local.admin.constants.AdminConstants;
import com.local.admin.pojo.AdminUser;
import com.local.admin.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;


/**
 * 后台首页控制器
 */

@Controller
@RequestMapping("/admin")
public class AdminIndexController {

    @Autowired
    private AdminUserService adminUserService;

    /**
     * 后台登录页面
     * @return
     */
    @GetMapping("/login")
    public String login() {
        return "admin/login";
    }

    /**
     * 提交登录
     * @return
     */
    @PostMapping("/login")
    public String login(
            @RequestParam("userName") String userName,
            @RequestParam("password") String password,
            @RequestParam("verifyCode") String verifyCode,
            HttpSession session) {
        if (!StringUtils.hasLength(verifyCode)) {
            session.setAttribute("errorMsg", "请输入验证码");
            return "admin/login";
        }
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            session.setAttribute("errorMsg", "请输入用户名和密码");
            return "admin/login";
        }

        //校验验证码
        String sessionVerifyCode = session.getAttribute(AdminConstants.ADMIN_LOGIN_CAPTCHA).toString();
        if (!verifyCode.equalsIgnoreCase(sessionVerifyCode)) {
            session.setAttribute("errorMsg", "验证码错误，请重新输入");
            return "admin/login";
        }

        AdminUser adminUser = adminUserService.login(userName, password);
        if (Objects.isNull(adminUser)) {
            //登录失败
            session.setAttribute("errorMsg", "登录失败，请检查用户名和密码");
            return "admin/login";
        } else {
            //登录成功
            session.setAttribute(AdminConstants.ADMIN_USER_SESSION_KEY, adminUser.getNickName());
            session.setAttribute(AdminConstants.ADMIN_USER_ID_SESSION_KEY, adminUser.getAdminUserId());
            //session过期时间设置为7200秒 即两小时
            //session.setMaxInactiveInterval(60 * 60 * 2);

            //移除session中的验证码
            session.removeAttribute(AdminConstants.ADMIN_LOGIN_CAPTCHA);

            return "redirect:/admin/index";
        }

    }

    @GetMapping({"/index", "/", ""})
    public String index(HttpServletRequest request) {
        request.setAttribute("path", "index");

        return "admin/index";
    }


    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(AdminConstants.ADMIN_USER_SESSION_KEY);
        request.getSession().removeAttribute(AdminConstants.ADMIN_USER_ID_SESSION_KEY);

        return "redirect:/admin/login";
    }


}
